/*
 * @Autor: dingxiaolin
 * @Date: 2021-06-02 13:12:43
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2021-07-21 13:37:57
 */
import { appMenus } from '@/api/system/menu'
import { constantRouterComponents } from './constantRouterComponents'
import router from '@/router/index'
import { routes } from '@/router/index'
import { notFound } from '@/router/modules/welcome'
// import { welcome } from '@/router/modules/welcome'
import { Empty } from 'ant-design-vue'
import common from '@/router/common'
import { RouteRecordRaw } from 'vue-router'
import { Modal, notification } from 'ant-design-vue'
import { storage } from '@/utils/Storage'
import { ACTIVE_APP } from '@/store/mutation-types'
const components = import.meta.globEager('../views/dynamic_view/**/*.vue')
/**
 * 异步生成菜单树， 方案一
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
export const listToTree = (list, tree, parentId) => {
    list.length > 0
        ? list.forEach((item) => {
            // 判断是否为父级菜单
            // eslint-disable-next-line eqeqeq
            if (item.pid == parentId) {
                const child = {
                    ...item,
                    key: item.key || item.name,
                    children: []
                }
                // 迭代 list， 找到当前菜单相符合的所有子菜单
                listToTree(list, child.children, item.id)
                // 删掉不存在 children 值的属性
                if (child.children.length <= 0) {
                    delete child.children
                }
                // 加入到树中
                tree.push(child)
            }
        })
        : []
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
    return routerMap.map(item => {
        // eslint-disable-next-line no-unused-vars
        const { title, show, hideChildren, hiddenHeaderContent, target, icon, link } = item.meta || {}
        const component = components[`../views/dynamic_view/${item.component}.vue`] ? components[`../views/dynamic_view/${item.component}.vue`].default : Empty
        const currentRouter = {
            // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
            path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
            // 路由名称，建议唯一
            name: item.name || item.key || '',
            // 该路由对应页面的 组件 :方案1
            // component: constantRouterComponents[item.component || item.key],
            // 该路由对应页面的  组件 :方案2 (动态加载)
            // component: item.component, //|| components[`../views/${item.component}.vue`].defualt
            component: constantRouterComponents[item.component || item.key] || component,
            // component: item.component,
            // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
            meta: {
                title: title,
                icon: icon || undefined,
                // hiddenHeaderContent: hiddenHeaderContent,
                target: target,
                keepAlive: false,
                link: link
            },
            hidden: false,//默认显示菜单
            hideChildrenInMenu: false,//默认不设置隐藏子菜单
            redirect: '',//默认不设置重定向
            children: [],//默认不设置子菜单
        }
        // 是否设置了隐藏菜单
        if (show === false) {
            currentRouter.hidden = true
        }
        // 是否设置了隐藏子菜单
        if (hideChildren) {
            currentRouter.hideChildrenInMenu = true
        }
        // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
        if (!currentRouter.path.startsWith('http')) {
            currentRouter.path = currentRouter.path.replace('//', '/')
        }
        // 重定向
        item.redirect && (currentRouter.redirect = item.redirect)
        // 是否有子菜单，并递归处理
        if (item.children && item.children.length > 0) {
            // Recursion
            currentRouter.children = generator(item.children, currentRouter)
        }
        return currentRouter
    })
}

/**
 * 异步生成菜单树， 方案二
 * @param dataList
 */
const list2tree = (items, parentId = -1, arr = [], pathPrefix = '') => {
    return items
        .filter((item) => item.pid == parentId)
        .map((item: any) => {
            const { icon, id, name, parentId, sort, keepAlive, meta, url } = item
            let path = url.startsWith('/') ? url : '/' + url
            path = url.startsWith(pathPrefix) ? path : pathPrefix + path
            path = [...new Set(path.split('/'))].join('/')

            // 路由对应的组件
            const component =
                constantRouterComponents[path] || Empty || (() => import('@/views/static_view/error/404.vue'))

            return {
                path: path,
                // 路由名称，建议唯一
                name: path || '',
                children: list2tree(items, item.id, [], path),
                // 该路由对应页面的 组件 (动态加载)
                component: component,
                props: true,
                // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
                meta: {
                    title: meta?.title || name,
                    icon: icon || 'icon-zhuomian',
                    // hiddenHeaderContent: hiddenHeaderContent,
                    // permission: item.actions || []
                    keepAlive: keepAlive == 1,
                    reload: false,
                    componentName: component.name,
                    // TODO 简单模拟CRUD权限：创建（Create）、更新（Update）、读取（Retrieve）和删除（Delete）操作，可以自行修改查看页面效果
                    permission:
                        parentId == -1
                            ? []
                            : ['create', 'update', 'retrieve', 'delete'].map(
                                (n) =>
                                    `${url
                                        .split('/')
                                        .filter((m) => m.trim() != '')
                                        .join('.')}.${n}`
                            )
                }
            }
        })
        .sort((a, b) => a.sort - b.sort)
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
    return new Promise((resolve, reject) => {
        const code = storage.get(ACTIVE_APP)
        //防重复获取路由菜单
        if (storage.get(code)) {
            const routers = generator(storage.get(code), [])
            const layout = routes.find((item) => item.name == 'Layout')!
            layout.children = [...common, ...routers]
            router.addRoute(layout)
            router.addRoute(notFound)
            resolve(routers)
            return;
        }
        appMenus({ application: code })
            .then((res: any) => {
                const childrenNav = []
                //      后端数据, 根级树数组,  根级 PID
                listToTree(res, childrenNav, 0)
                console.log(childrenNav, '根据后端返回的权限路由生成')
                storage.set(code, childrenNav)
                const routers = generator(childrenNav, [])
                console.log(routers, '整理后的菜单')
                const layout = routes.find((item) => item.name == 'Layout')!
                layout.children = [...common, ...routers]
                router.addRoute(layout)
                router.addRoute(notFound)
                resolve(routers)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
